package com.controller.sys.user;

import com.common.ErrorCodeEnum;
import com.model.base.Result;
import com.common.anntation.Log;
import com.common.emums.BusinessType;
import com.common.emums.DataStatus;

import com.common.excel.ExcelUtil;
import com.common.exception.BusinessException;
import com.common.utils.EntityConversionUtil;
import com.common.utils.Md5Utils;
import com.common.utils.StringUtils;
import com.common.utils.Utils;
import com.core.springSecurity.service.PermissionService;
import com.model.pojo.sys.SysDept;
import com.model.pojo.sys.SysUser;
import com.model.pojo.excel.UserExcel;
import com.service.sys.SysDeptService;
import com.service.sys.SysUserService;
import com.model.vo.sys.user.ErrorUserVO;
import com.model.vo.sys.user.ImportUserInfoVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: zql
 * @Description: 导入用户模块
 * @Data: 15:23 2021/7/9
 */

@Api(tags = {"用户"})
@Slf4j
@RestController
@RequestMapping("/v1")
public class ImportUserController {
    @Resource
    SysUserService sysUserService;

    @Resource
    SysDeptService sysDeptService;
    /**
     * @Author: zql
     * @Description: 导入用户表
     * @param excel 用户表文件
     * @Data: 8:39 2021/6/3
     */
    @ApiOperation(value = "导入用户表")
    @Log(title = "导入用户表" ,businessType = BusinessType.IMPORT)
    @PostMapping(value = "/importUserInfo")
    @PreAuthorize("@ss.hasAnyPermi('" + PermissionService.SYSTEM_OPERATE + "')")
    public Result<ImportUserInfoVO> importUserInfo(
            @ApiParam(name = "excel", value = "用户表", required = true)
            @RequestParam("file") MultipartFile excel){
        if(StringUtils.isNull(excel)){
            return Result.fail(ErrorCodeEnum.EXCEL_NOT_FOUNT);
        }

        List<UserExcel> userExcelList = ExcelUtil.readExcel(excel,  1, 1,UserExcel.class);
        List<SysUser> sysUserList = new ArrayList<>();
        List<ErrorUserVO> errorUserVOList = new ArrayList<>();
        //表自检：去重
        List<String> mobiles=new ArrayList<>();
        List<String> names = new ArrayList<>();
        List<String> emails = new ArrayList<>();
        assert userExcelList != null;
        userExcelList = userExcelList.stream().filter(o-> {
            String name= Utils.verifyNullMember(o,"sysUserId");
            if(!"".equals(name)) {
                errorUserVOList.add(EntityConversionUtil.copy(o, ErrorUserVO.class).errMsg("字段" + name + "为空"));
                log.error("字段{}为空", name);
                return false;
            }
           if (StringUtils.isNotEmpty(o.getMobile()) && mobiles.contains(o.getMobile())) {
               errorUserVOList.add(EntityConversionUtil.copy(o, ErrorUserVO.class).errMsg("导入的表中存在重复的手机号"));
               log.error("导入的表中存在重复的手机号:{}", o.getMobile());
               return false;
           }
            if (StringUtils.isNotEmpty(o.getEmail()) && emails.contains(o.getEmail())) {
                errorUserVOList.add(EntityConversionUtil.copy(o, ErrorUserVO.class).errMsg("导入的表中存在重复的邮箱"));
                log.error("导入的表中存在重复的邮箱:{}", o.getEmail());
                return false;
            }
           if (names.contains(o.getName())) {
               errorUserVOList.add(EntityConversionUtil.copy(o, ErrorUserVO.class).errMsg("导入的表中存在重复的登录名"));
               log.error("导入的表中存在重复的登录名:{}", o.getName());
               return false;
           }
           emails.add(o.getEmail());
           mobiles.add(o.getMobile());
           names.add(o.getName());
           return true;
       }).collect(Collectors.toList());

        for (UserExcel userExcel: userExcelList) {
            SysUser sysUser = EntityConversionUtil.copy(userExcel,SysUser.class);
            if(StringUtils.isNotEmpty(userExcel.getPassword())) {
                sysUser.setPassword(sysUserService.encode(Md5Utils.toUpperCase32(userExcel.getPassword())));
            }
            try {
                SysDept sysDept = sysDeptService.getByName(userExcel.getDeptName(), DataStatus.OK.getCode());
                if(StringUtils.isNull(sysDept)){
                    throw new BusinessException(ErrorCodeEnum.ERROR_MESSAGE.setParam("该("+userExcel.getDeptName()+")部门不存在或已停用/删除"));
                }
                sysUser.setSysDeptId(sysDept.getSysDeptId());
                sysUserService.verifyUserInfo(sysUser,StringUtils.isNotNull(sysUser.getSysUserId()));
            }catch (BusinessException e){
                errorUserVOList.add(EntityConversionUtil.copy(sysUser, ErrorUserVO.class).errMsg(e.getErrorCodeEnum().getErrorMsg()));
                log.error("{}", e.getErrorCodeEnum().getErrorMsg());
                continue;
            }
            sysUserList.add(sysUser);
        }
        if (sysUserList.size()>0){
            sysUserService.updateAndInsert(sysUserList);
        }
        return Result.suc(ImportUserInfoVO.builder().importSuccess(sysUserList.size()).errorList(errorUserVOList).build());
    }


}
